﻿using FellowOakDicom;
using FellowOakDicom.Imaging.Codec;
using LS.DicomViewer.Common;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace LS.Dicom.Tools
{
    public class FileTransInfo : BindableObject<FileTransInfo>
    {
        string patientName;

        public string PatientName
        {
            get => patientName;
            set => SetProperty(ref patientName, value);
        }

        string fileName;
        public string FileName
        {
            get => fileName;
            set => SetProperty(ref fileName, value);
        }
        string filePath;
        public string FilePath
        {
            get => filePath;
            set => SetProperty(ref filePath, value);
        }
        bool transposed = false;
        public bool Transposed
        {
            get => transposed;
            set => SetProperty(ref transposed, value);
        }

        string remark;
        public string Remark
        {
            get => remark;
            set => SetProperty(ref remark, value);
        }

        public FileTransInfo(string file)
        {
            filePath = file;
            fileName = Path.GetFileName(file);
            if (file.Contains("]-"))
            {
                PatientName = file.Split("-")[0];
                PatientName = Path.GetFileNameWithoutExtension(PatientName);
            }
        }
    }
    public class DicomTransfromViewModel : BindableObject<DicomTransfromViewModel>
    {
        ObservableCollection<FileTransInfo> fileTransInfos = new ObservableCollection<FileTransInfo>();

        public ObservableCollection<FileTransInfo> FileTransInfos
        {
            get => fileTransInfos;
            set => SetProperty(ref fileTransInfos, value);
        }

        string targetFolder;

        public string TargetFolder
        {
            get => targetFolder;
            set => SetProperty(ref targetFolder, value);
        }

        public UICommand SelectCommamd { get; set; }

        public UICommand TransCommand { get; set; }

        public DicomTransfromViewModel()
        {
            SelectCommamd = new UICommand(SelectFile);
            TransCommand = new UICommand(async () => await Transform(), a => fileTransInfos.Count > 0);
        }
        public void SelectFile()
        {
            var folderBrowserDialog = new FolderBrowserDialog();
            if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
            {
                var folder = folderBrowserDialog.SelectedPath;
                LoadFile(folder);
            }
            TransCommand.NotifyCanExecuteChanged();
        }

        void LoadFile(string folder)
        {
            var dicomFiles = Directory.GetFiles(folder, "*.dcm");
            dicomFiles.ToList().ForEach(a => FileTransInfos.Add(new FileTransInfo(a)));
            var dirs = Directory.GetDirectories(folder);
            foreach (var dir in dirs)
            {
                LoadFile(dir);
            }
        }

        public async Task Transform()
        {
            var folderBrowserDialog = new FolderBrowserDialog();
            if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
            {
                TargetFolder = folderBrowserDialog.SelectedPath;
                await Task.Run(async () =>
                {
                    foreach (var item in FileTransInfos)
                    {
                        await Dispatcher.BeginInvoke(async () => await DicomTrans(item));
                        Thread.Sleep(500);
                    }
                });
            }
        }

        private async Task DicomTrans(FileTransInfo fileTransInfo)
        {
            var file = await DicomFile.OpenAsync(fileTransInfo.FilePath);
            if (file == null)
            {
                fileTransInfo.Remark = "加载文件异常，请检查文件是否正确！";
                return;
            }
            if (file.Dataset.Contains(DicomTag.PixelData))
            {
                if (file.Dataset.InternalTransferSyntax != DicomTransferSyntax.JPEGProcess1)//非压缩的文件
                {
                    var patientName = file.Dataset.GetString(DicomTag.PatientName);
                    var targetFile = file.Clone(DicomTransferSyntax.JPEGProcess1);
                    var targetPath = Path.Combine(TargetFolder, patientName);
                    if (!Directory.Exists(targetPath))
                    {
                        Directory.CreateDirectory(targetPath);
                    }
                    var targetFilePath = Path.Combine(TargetFolder, patientName, fileTransInfo.FileName);
                    if (File.Exists(targetFilePath))
                    {
                        fileTransInfo.Transposed = true;
                        return;
                    }
                    targetFile.Save(targetFilePath);
                    await Dispatcher.BeginInvoke(() =>
                    {
                        fileTransInfo.Transposed = true;
                        fileTransInfo.PatientName = patientName;
                        fileTransInfo.Remark = "完成";
                    });
                }
            }
        }
    }
}
